
var nowPage = 1;
var user = null;

//layui的element

function loadData(){
    checkLogin();
}



function loadReply() {
    loadReplyBase(1);
}
function loadReplyBase(number) {
    $.ajax({
        url: 'http://localhost:8080/reply/simpleMsgList',
        async:false,
        method: 'POST',
        crossDomain: true,
        xhrFields: { withCredentials: true },
        data:{
            nowPage:number,
            numPerPage:10
        },
        success: function (msg) {
            if(msg.code !== 0){
                layer.msg(msg.msg);
            }
            console.log(msg.data);
            let $reply = $("#reply-list");
            $reply.empty();
            $reply.append();
            $(msg.data.postList).each(function (i,e){
                let str = "<div class='post-item'>";
                str += "<div class='post-title' onclick='toPost("+e.id+")' >  " + e.title + "</div>";
                str += "<div class=\"reply-count\">" + e.replyCount + "</div>";
                str += "<div class=\"create-time\">"+e.createTime+"</div>";
                str += "<div class=\"btn-group\">";
                str += "<button class=\"my-button danger\" onclick=\"deletePost("+e.id+")\">删除</button>";
                str += "</div></div>";
                $reply.append(str);
            });
            attachPager(msg.data.pageList,page)
        },error: function (error){
            layer.msg('帖子加载失败了');
        }
    })
}

function loadNotice() {
    loadNoticeBase(1);
}

function loadNoticeBase(page) {
    $.ajax({
        url: 'http://localhost:8080/notice/simpleMsgList',
        async:false,
        method: 'POST',
        crossDomain: true,
        xhrFields: { withCredentials: true },
        data:{
            nowPage:page,
            numPerPage:10
        },
        success: function (msg) {
            if(msg.code !== 0){
                layer.msg(msg.msg);
            }
            console.log(msg.data);
            let $notice = $("#notice-list");
            $notice.empty();
            $notice.append();
            $(msg.data.postList).each(function (i,e){
                let str = "<div class='notice-item'>";
                str += "<div class='notice-content'> " + e.content + "</div>";
                str += "<div class=\"create-time\">"+e.createTime+"</div>";
                str += "<div class=\"btn-group\">";
                str += "<button class=\"my-button danger\" onclick=\"deleteNotice("+e.id+")\">删除</button>";
                str += "</div></div>";
                $notice.append(str);
            });
            attachPager(msg.data.pageList,page)
        },error: function (error){
            layer.msg('消息加载失败了');
        }
    })
}



layui.use('element',function(){
    var elem = layui.element;
    console.log(elem)
    loadPost();
    elem.on('tab(msg-list)',function (data){
        console.log(data);
        let tabName = $(this).text();
        console.log()
        if (tabName === '我的帖子'){
            loadPost();
        }
        if(tabName === '我的回复'){
            loadReply();
        }
        if(tabName === '我的通知'){
            loadNotice();
        }
    });
})

function deletePost(postId){
    layer.confirm("确定要删除这个帖子吗？",{
        btn: ['确定','关闭']
    },function (){
        $.post({
            url: 'http://localhost:8080/post/deleteById',
            async:false,
            method: 'POST',
            crossDomain: true,
            xhrFields: { withCredentials: true },
            data:{
                id: postId,
                userId:user.base.id
            },
            success: function (msg) {
                layer.msg("删除成功");
                window.location.href='../block/detail.html?id=' + blockId;
            },error: function (error){
                layer.msg("删除失败");
                window.location.reload()
            }
        })
    });
}

function deleteNotice(noticeId){
    $.post({
        url: 'http://localhost:8080/notice/deleteById',
        async:false,
        method: 'POST',
        crossDomain: true,
        xhrFields: { withCredentials: true },
        data:{
            id: noticeId
        },
        success: function (msg) {
            layer.msg("删除成功");

        },error: function (error){
            layer.msg("删除失败");
        }
    });
    window.location.reload()

}





function loadPost(){
    //为了节省时间，不保存每个标签状态了，直接清空然后重新加载
    loadPostBase(1);
}
function loadPostBase(page){
    $.ajax({
        url: 'http://localhost:8080/post/simpleMsgList',
        async:false,
        method: 'POST',
        crossDomain: true,
        xhrFields: { withCredentials: true },
        data:{
            nowPage:page,
            numPerPage:10
        },
        success: function (msg) {
            if(msg.code !== 0){
                layer.msg(msg.msg);
            }
            console.log(msg.data);
            let $post = $("#post-list");
            $post.empty();
            $post.append();
            $(msg.data.postList).each(function (i,e){
                let str = "<div class='post-item'>";
                str += "<div class='post-title' onclick='toPost("+e.id+")' >  " + e.title + "</div>";
                str += "<div class=\"reply-count\">" + e.replyCount + "</div>";
                str += "<div class=\"create-time\">"+e.createTime+"</div>";
                str += "<div class=\"btn-group\">";
                str += "<button class=\"my-button danger\" onclick=\"deletePost("+e.id+")\">删除</button>";
                str += "</div></div>";
                $post.append(str);
            });
            attachPager(msg.data.pageList,page)
        },error: function (error){
            layer.msg('帖子加载失败了');
        }
    })
}

function toPost(id){
    window.location.href="../post/detail.html?id="+id;
}





function attachPager(pageList, num) {
    $(".page-list").html("");
    maxPage = parseInt(pageList[pageList.length - 1]);
    $(pageList).each(function (i, e) {
        let str = "<div class="
        if (e === num.toString()) {
            str += "'my-button-now'";
        } else {
            str += "'my-button'";
        }
        if (e !== '...') {
            str += "onclick='loadPage(" + e + ")'"
        }
        str += "/>" + e + "</div>";
        $(".page-list").append(str);
    })
}

function lastPage() {
    let tPage = $(".my-button-now").text();
    console.log(tPage)
    let nowPage = parseInt(tPage);
    if (nowPage <= 1) {
        layer.msg("没有了");
        return;
    }
    loadPage(nowPage - 1);
}

function nextPage() {

    let tPage = $(".my-button-now").text();
    console.log(tPage)
    let nowPage = parseInt(tPage);
    if (nowPage >= maxPage) {
        layer.msg("没有了");
        return;
    }
    loadPage(nowPage + 1);
}

function jumpToPage() {
    let tPage = $("#jump-input").val();
    console.log(tPage);
    let page = parseInt(tPage);
    console.log(typeof (page))
    console.log(page)
    if (page < 1 || page > maxPage || isNaN(page)) {
        return;
    }
    loadPage(page);
}

function loadPage(page){
    $.ajax({
        url: backBaseUrl + "/postReply/getPostPage",
        type:"post",
        data:{
            "postId":post.id,
            "curPage":page,
            "numPerPage":10
        },
        success: function (msg){
            console.log(msg)
            $("#content").empty();
            if(page === 1){
                loadOneReply(window.posterInfo,window.post);
            }
            $(msg.data.replyList).each(function (i,e){
                loadOneReply(e.user,e.reply);
            })
            attachPager(msg.data.pageList,page);
        }
    })
}

function appendNextPage(){
    let tPage = $(".my-button-now").text();
    console.log(tPage)
    let nowPage = parseInt(tPage);
    if (nowPage >= maxPage) {
        // layer.msg("没有了");
        console.log("没有了 ")
        return;
    }
    loadPage(tPage)
}


/**
 * 如果用户没有登录，就禁用用户发帖的权限
 *
 *
 *
 * */
function checkLogin(){
    // console.log("checking login")
    $.post({
        url: 'http://localhost:8080/login/checkLogin',
        async:false,
        method: 'POST',
        crossDomain: true,
        xhrFields: { withCredentials: true },
        success: function (msg) {
            let user = msg.data.user;
            if(user !== undefined && user !== null){ console.log("user saved"); window.user = user;}
        }, error: function (error) {
            layer.msg("登录信息获取失败~");
            console.log(error)
        }
    })
}